package io.vertx.examples.mongo

import io.vertx.core.AbstractVerticle
import io.vertx.core.AsyncResult
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.ext.mongo.MongoClient
import io.vertx.kotlin.ext.auth.pubSecKeyOptionsOf

class MongoClientVerticle : AbstractVerticle() {
    lateinit var mongoClient: MongoClient

    @Throws(Exception::class)
    override fun start() {
        var uri = "mongodb://eliza:eliza@192.168.20.130:27017"

//        mongodb://userName:password@host/?authSource=databaseName&ssh=true;
//        mongodb://192.168.20.129:27017
        var db = "mong"//数据库名

        val mongoconfig = JsonObject()
            .put("connection_string", uri)
            .put("db_name", db)
        //指定池源名称
        val mongoClient = MongoClient.createShared(vertx, mongoconfig, "MyPoolName")
        del(mongoClient)
        save(mongoClient)
        insert(mongoClient)
    }

    fun del(mongoClient: MongoClient) {
        mongoClient.dropCollection("mong") { ar ->
            ar?.let {
                println(ar)
            }

        }
    }

    fun save(mongoClient: MongoClient) {
        //保存文档
        val document = JsonObject()
            .put("title", "The Hobbit")
            .put("author", "okkk")
        mongoClient.save("books", document) { res: AsyncResult<String> ->
            if (res.succeeded()) {
                val id = res.result()
                println("Saved book with id $id")
            } else {
                res.cause().printStackTrace()
            }
        }
    }

    fun insert(mongoClient: MongoClient) {
        val document = JsonObject()
            .put("title", "The Hobbit")
        mongoClient.insert("books", document) { res ->
            if (res.succeeded()) {
                val id: String = res.result()
                println("Inserted book with id $id")
            } else {
                res.cause().printStackTrace()
            }
        }
    }

    companion object {
        /*
  Convenience method so you can run it in your IDE
   */
        @JvmStatic
        fun main(args: Array<String>) {
            Vertx.vertx().deployVerticle(MongoClientVerticle::class.java.name)
        }
    }
}